<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <canvas id="canvas" width=400 height=400></canvas>
</body>

</html>
<script>
  /** @type {HTMLCanvasElement} */
  let canvas = document.getElementById('canvas');
  let gl = canvas.getContext('webgl');
  gl.clearColor(0.1, 0.5, 0.4, 0.3);
  gl.clear(gl.COLOR_BUFFER_BIT);

  function initShader(gl, vertexSource, fragmentSource) {
    // 创造着色器对象
    let vertexShader = gl.createShader(gl.VERTEX_SHADER);
    let fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
    gl.shaderSource(vertexShader, vertexSource);
    gl.shaderSource(fragmentShader, fragmentSource)
    gl.compileShader(vertexShader);
    gl.compileShader(fragmentShader);
    let program = gl.createProgram();
    gl.attachShader(program, vertexShader)
    gl.attachShader(program, fragmentShader)
    gl.linkProgram(program);
    gl.useProgram(program);
    return program
  }
  let vertexSource = `
    attribute vec4 position;
    attribute vec4 color;


    varying vec4 v_f_color123;
    void main(){
      gl_Position = position;
      v_f_color123 = color;
    }
  `;
  let fragmentSource = `
    precision lowp float;
    varying vec4 v_f_color123;
    void main(){
      gl_FragColor = v_f_color123;
    }
  `;
  let program = initShader(gl, vertexSource, fragmentSource);
  let positionIndex = gl.getAttribLocation(program,'position');
  let colorIndex = gl.getAttribLocation(program,'color');

  let data = new Float32Array([
    -0.5,0.0,0.0,
    0.5,0.0,0.0
  ])


  let buffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER,buffer);
  gl.bufferData(gl.ARRAY_BUFFER,data,gl.STATIC_DRAW);
  gl.vertexAttribPointer(positionIndex,3,gl.FLOAT,false,0,0);
  gl.enableVertexAttribArray(positionIndex);

  let colorData = new Float32Array([
    1.0,0.0,0.0,
    0.0,1.0,0.0
  ])
  let colorBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER,colorBuffer);
  gl.bufferData(gl.ARRAY_BUFFER,colorData,gl.STATIC_DRAW);
  gl.vertexAttribPointer(colorIndex,3,gl.FLOAT,false,0,0);
  gl.enableVertexAttribArray(colorIndex);

  gl.drawArrays(gl.LINES,0,2);
</script>